#include <iostream>
#include <cmath>
using namespace std;

// 才智基函数
double phi1(double x, double sigma) {
    return exp(-x * x / (2 * sigma * sigma));
}

// 导数 d(phi1)/dx
double d_phi1_dx(double x, double sigma) {
    return (-x / (sigma * sigma)) * exp(-x * x / (2 * sigma * sigma));
}

// 逆解 x 从 p
double inverse_x_from_p(double p, double sigma, double tolerance = 1e-6, int max_iter = 100) {
    double x = 1.0; // 初始猜测
    for (int i = 0; i < max_iter; ++i) {
        double current_p = d_phi1_dx(x, sigma);
        if (fabs(current_p - p) < tolerance) break;
        double derivative = (-1 / (sigma * sigma) + x * x / (sigma * sigma * sigma * sigma)) * exp(-x * x / (2 * sigma * sigma));
        x -= (current_p - p) / derivative; // 牛顿法更新
    }
    return x;
}

// 勒让德变换
double legendreTransform(double p, double sigma) {
    double x = inverse_x_from_p(p, sigma);
    return p * x - phi1(x, sigma);
}

int main() {
    double p = -0.5, sigma = 1.0;
    cout << "勒让德变换结果: " << legendreTransform(p, sigma) << endl;
    return 0;
}